<?php

/**
 * QPHP
 *
 * Copyright (c) 2022 QPHP
 *
 * @author lbnnbs
 * @copyright Copyright (c) 2022 lbnnbs QPHP (https://gitee.com/lbnnbs/qphp)
 * @license AGPLv3 License
 *
 * 使用Redis接管Session
 */
class RedisSession implements SessionHandlerInterface {
    
    public function open($path, $name) {
        return true;
    }
    
    public function close() {
        return true;
    }
    
    public function read($id) {
        try {
            $result = Rd()->get('PHPREDIS_SESSION:' . $id);
            if (!$result) {
                $result = '';
            }
            return strval($result);
        } catch (\RedisException $e) {
            wlog($e->getMessage(), 'redis');
            return '';
        }
    }
    
    public function write($id, $data) {
        $expire_time = 1440;
        $config = \Sys::getCfg('session');
        if ($config && isset($config['expire']) && intval($config['expire'])) {
            $expire_time = $config['expire'];
        }
        try {
            return Rd()->setex('PHPREDIS_SESSION:' . $id, $expire_time, $data);
        } catch (\RedisException $e) {
            wlog($e->getMessage(), 'redis');
            return false;
        }
    }
    
    public function destroy($id) {
        try {
            return Rd()->del($id);
        } catch (\RedisException $e) {
            wlog($e->getMessage(), 'redis');
            return false;
        }
    }
    
    public function gc($maxlifetime) {
        return true;
    }
    
    public function __destruct() {
        session_write_close();
    }
}